<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="姓名" v-bind="validateInfos.name">
            <a-input v-model:value="formData.name" placeholder="请输入姓名" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="头像" v-bind="validateInfos.avatar">
            <j-image-upload :fileMax="1" v-model:value="formData.avatar" :disabled="disabled"></j-image-upload>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="微信ID" v-bind="validateInfos.openid">
            <a-input v-model:value="formData.openid" placeholder="请输入微信ID" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <!-- <a-col :span="24">
          <a-form-item label="unionid" v-bind="validateInfos.unionid">
            <a-input v-model:value="formData.unionid" placeholder="请输入unionid" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col> -->
        <a-col :span="24">
          <a-form-item label="身份证" v-bind="validateInfos.idcard">
            <a-input v-model:value="formData.idcard" placeholder="请输入身份证" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="手机号" v-bind="validateInfos.phone">
            <a-input v-model:value="formData.phone" placeholder="请输入手机号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="状态" v-bind="validateInfos.status">
            <j-switch :disabled="disabled" checked-children="有效" un-checked-children="无效" :options="['1', '0']"
              v-model:value="formData.status">
            </j-switch>
            <!-- <a-input v-model:value="formData.status" placeholder="请输入状态" :disabled="disabled"></a-input> -->
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="性别" v-bind="validateInfos.sex">
            <a-input v-model:value="formData.sex" placeholder="请输入性别" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否专家" v-bind="validateInfos.isExpert">
            <j-switch :disabled="disabled" checked-children="是" un-checked-children="否" :options="['1', '0']"
              v-model:value="formData.isExpert">
            </j-switch>
            <!-- <a-input v-model:value="formData.isExpert" placeholder="请输入是否专家" :disabled="disabled"></a-input> -->
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否健康管家" v-bind="validateInfos.isHealth">
            <j-switch :disabled="disabled" checked-children="是" un-checked-children="否" :options="['1', '0']"
              v-model:value="formData.isHealth">
            </j-switch>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="职业" v-bind="validateInfos.job">
            <a-input v-model:value="formData.job" placeholder="请输入职业" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否上架" v-bind="validateInfos.validate">
            <a-select v-model:value="formData.validate" placeholder="请选择是否上架" :disabled="disabled">
              <a-select-option value="1">是</a-select-option>
              <a-select-option value="0">否</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="专家费用" v-bind="validateInfos.fee">
            <a-input-number v-model:value="formData.fee" placeholder="请输入专家费用" style="width: 100%"
              :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="医院" v-bind="validateInfos.hospital">
            <a-select
              v-model:value="formData.hospital"
              placeholder="请选择医院"
              :disabled="disabled"
              :options="hospitalOptions"
              :field-names="{ label: 'label', value: 'value' }"
              show-search
              :filter-option="filterHospitalOption"
              @change="handleHospitalChange"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="医院名称" v-bind="validateInfos.hospitalname">
            <a-input v-model:value="formData.hospitalname" placeholder="选择医院后自动填充" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="项目组" v-bind="validateInfos.projectid">
            <a-tree-select
              v-model:value="formData.projectid"
              :tree-data="projectTreeData"
              :field-names="{ label: 'title', value: 'value', children: 'children' }"
              :disabled="!formData.hospital || disabled"
              :placeholder="formData.hospital ? '请选择项目组' : '请先选择医院'"
              show-search
              tree-node-filter-prop="title"
              @change="handleProjectChange"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="项目组名称" v-bind="validateInfos.projectname">
            <a-input v-model:value="formData.projectname" placeholder="选择项目组后自动填充" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否显示微信" v-bind="validateInfos.isShow">
            <j-switch :disabled="disabled" checked-children="是" un-checked-children="否" :options="['1', '0']"
              v-model:value="formData.isShow">
            </j-switch>
            <!-- <a-input v-model:value="formData.isShow" placeholder="请输入是否显示微信" :disabled="disabled"></a-input> -->
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="工作年限" v-bind="validateInfos.life">
            <a-input-number v-model:value="formData.life" placeholder="请输入工作年限" style="width: 100%"
              :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="服务人数" v-bind="validateInfos.serverNumber">
            <a-input-number v-model:value="formData.serverNumber" placeholder="请输入服务人数" style="width: 100%"
              :disabled="disabled" />
          </a-form-item>
        </a-col>
        <!-- <a-col :span="24">
          <a-form-item label="地区" v-bind="validateInfos.area">
            <a-input v-model:value="formData.area" placeholder="请输入地区" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="地区名称" v-bind="validateInfos.areaName">
            <a-input v-model:value="formData.areaName" placeholder="请输入地区名称" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col> -->
        <a-col :span="24">
          <a-form-item label="评级" v-bind="validateInfos.rate">
            <a-input-number v-model:value="formData.rate" placeholder="请输入评级" style="width: 100%"
              :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="简介" v-bind="validateInfos.profile">
            <a-textarea v-model:value="formData.profile" :rows="4" placeholder="请输入简介" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <!-- <a-col :span="24">
          <a-form-item label="佣金比例" v-bind="validateInfos.ratio">
            <a-input-number v-model:value="formData.ratio" placeholder="请输入佣金比例" style="width: 100%"
              :disabled="disabled" />
          </a-form-item>
        </a-col> -->

      </a-row>
    </a-form>
    <!-- <NurseHospital @register="registerModal">
    </NurseHospital> -->
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed } from 'vue';

  import { getValueType } from '/@/utils';
  import { saveOrUpdate, getDepartName, queryAllTreeListByPid } from '../NurseNurses.api';
  import { Form } from 'ant-design-vue';
  import JSwitch from '/@/components/Form/src/jeecg/components/JSwitch.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import { defHttp } from '/@/utils/http/axios';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formBpm: { type: Boolean, default: true },
  });

  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    name: '',
    avatar: '',
    openid: '',
    unionid: '',
    idcard: '',
    phone: '',
    status: '1',
    sex: '',
    isShow: '',
    life: undefined,
    serverNumber: undefined,
    area: '',
    areaName: '',
    rate: undefined,
    profile: '',
    ratio: undefined,
    isExpert: '',
    isHealth: '',
    job: '',
    validate: '',
    fee: undefined,
    hospital: '',
    hospitalname: '',
    projectid: '',
    projectname: '',
  });
  // const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const projectTreeData = ref<any[]>([]);
  const hospitalOptions = ref<any[]>([]);

  //表单验证
  const validatorRules = {
    name: [{ required: true, message: '请输入姓名!' }],
    // phone: [{ required: true, message: '请输入手机号!' },],
    // status: [{ required: true, message: '请输入状态!' },],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 医院选项搜索过滤
  function filterHospitalOption(input, option) {
    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  }

  // 加载医院选项（获取完整的医院数据，包括 sysOrgCode）
  async function loadHospitalOptions() {
    try {
      // 添加分页参数，获取所有医院数据
      const result = await defHttp.get({
        url: '/nurse_hospital/nurseHospital/rootList',
        params: {
          pageNo: 1,
          pageSize: 9999, // 设置一个很大的值来获取所有数据
        },
      });
      console.log('加载医院列表结果:', result);
      if (result && result.records && Array.isArray(result.records)) {
        hospitalOptions.value = result.records.map((item) => ({
          value: item.id,
          label: item.name,
          text: item.name,
          sysOrgCode: item.sysOrgCode, // 保存 sysOrgCode 用于后续查询
        }));
        console.log('医院选项已加载，共 ' + hospitalOptions.value.length + ' 条:', hospitalOptions.value);
      }
    } catch (error) {
      console.error('加载医院选项失败:', error);
    }
  }

  // 医院选择改变事件
  async function handleHospitalChange(value) {
    console.log('医院选择改变:', value);
    console.log('当前医院选项列表:', hospitalOptions.value);

    // 获取医院信息
    const hospital = hospitalOptions.value.find((item) => item.value === value);
    console.log('找到的医院对象:', hospital);

    if (hospital) {
      formData.hospitalname = hospital.text || hospital.label;
      console.log('写入医院名称:', formData.hospitalname);
    }

    // 清空项目组
    formData.projectid = '';
    formData.projectname = '';
    projectTreeData.value = [];

    // 加载项目组数据 - 根据医院的 sys_org_code 查询
    if (value && hospital && hospital.sysOrgCode) {
      try {
        console.log('使用 sysOrgCode 查询部门:', hospital.sysOrgCode);

        // 第一步：调用 getDepartName 接口，参数为 orgCode
        const departResult = await getDepartName({ orgCode: hospital.sysOrgCode });
        console.log('getDepartName 返回结果:', departResult);

        if (departResult && departResult.id) {
          // 第二步：使用返回的 id 作为 pid 调用 queryAllTreeListByPid 查询树形结构
          const treeResult = await queryAllTreeListByPid({ pid: departResult.id });
          console.log('queryAllTreeListByPid 返回结果:', treeResult);

          // 转换为树形选择器需要的格式
          if (treeResult && Array.isArray(treeResult)) {
            projectTreeData.value = convertToTreeData(treeResult);
            console.log('转换后的树形数据:', projectTreeData.value);
          }
        } else {
          console.warn('getDepartName 未返回有效的 id');
        }
      } catch (error) {
        console.error('加载项目组数据失败:', error);
      }
    } else {
      console.warn('无法加载项目组数据 - value:', value, 'hospital:', hospital, 'sysOrgCode:', hospital?.sysOrgCode);
    }
  }

  // 转换部门数据为树形选择器格式
  function convertToTreeData(data) {
    if (!Array.isArray(data)) return [];

    return data.map((item) => {
      const nodeId = item.id || item.key || item.value;
      const nodeTitle = item.departName || item.name || item.title || item.label;

      return {
        title: nodeTitle,
        key: nodeId,
        value: nodeId,
        children: item.children && item.children.length > 0 ? convertToTreeData(item.children) : undefined,
      };
    });
  }

  // 项目组选择改变事件
  function handleProjectChange(value, label, extra) {
    console.log('项目组选择改变 - value:', value);
    console.log('项目组选择改变 - label:', label);
    console.log('项目组选择改变 - extra:', extra);

    // 查找选中的项目组节点
    const findNode = (nodes, targetKey) => {
      for (const node of nodes) {
        if (node.key === targetKey) {
          return node;
        }
        if (node.children && node.children.length > 0) {
          const found = findNode(node.children, targetKey);
          if (found) return found;
        }
      }
      return null;
    };

    const selectedNode = findNode(projectTreeData.value, value);
    if (selectedNode) {
      formData.projectname = selectedNode.title;
      console.log('写入项目组名称:', formData.projectname);
    } else if (Array.isArray(label) && label.length > 0) {
      formData.projectname = label[label.length - 1];
    } else if (typeof label === 'string') {
      formData.projectname = label;
    }

    console.log('写入项目组ID:', value);
    console.log('写入项目组名称:', formData.projectname);
  }

  // 表单禁用
  const disabled = computed(() => {
    return props.formDisabled;
  });

  /**
   * 新增
   */
  async function add() {
    await loadHospitalOptions();
    await edit({});
  }

  /**
   * 编辑
   */
  async function edit(record) {
    // 先加载医院选项
    await loadHospitalOptions();

    // 等待下一个tick再处理数据
    await nextTick(async () => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if (record.hasOwnProperty(key)) {
          tmpData[key] = record[key];
        }
      });

      //赋值
      Object.assign(formData, tmpData);

      console.log('编辑数据:', record);
      console.log('表单数据:', formData);
      console.log('医院ID:', formData.hospital);
      console.log('项目组ID:', formData.projectid);

      // 如果有医院ID，加载项目组数据
      if (formData.hospital) {
        // 等待一下确保 hospitalOptions 已经加载完成
        await nextTick();

        const hospital = hospitalOptions.value.find((item) => item.value === formData.hospital);
        console.log('找到的医院信息:', hospital);

        if (hospital && hospital.sysOrgCode) {
          try {
            console.log('编辑时使用 sysOrgCode 查询部门:', hospital.sysOrgCode);

            // 第一步：调用 getDepartName 接口，参数为 orgCode
            const departResult = await getDepartName({ orgCode: hospital.sysOrgCode });
            console.log('编辑时 getDepartName 返回结果:', departResult);

            if (departResult && departResult.id) {
              // 第二步：使用返回的 id 作为 pid 调用 queryAllTreeListByPid 查询树形结构
              const treeResult = await queryAllTreeListByPid({ pid: departResult.id });
              console.log('编辑时 queryAllTreeListByPid 返回结果:', treeResult);

              // 转换为树形选择器需要的格式
              if (treeResult && Array.isArray(treeResult)) {
                projectTreeData.value = convertToTreeData(treeResult);
                console.log('编辑时转换后的树形数据:', projectTreeData.value);
              }
            }
          } catch (error) {
            console.error('编辑时加载项目组数据失败:', error);
          }
        } else {
          console.warn('编辑时未找到医院信息或 sysOrgCode', { hospital, formDataHospital: formData.hospital });
        }
      }
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = { ...formData };

    // 字段映射：将 hospitalid 映射回 hospital 字段
    if (model.hospitalid) {
      model.hospital = model.hospitalid;
    }

    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }

    console.log('提交数据:', model);

    await saveOrUpdate(model, isUpdate.value)
      .then(() => {
        emit('ok');
        resetFields();
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    height: 500px !important;
    overflow-y: auto;
    padding: 14px;
  }
</style>
